package com.atguigu.educenter.controller;


import com.atguigu.commonutils.JwtUtils;
import com.atguigu.commonutils.R;
import com.atguigu.commonutils.ordervo.UcenterMemberOrder;
import com.atguigu.educenter.entity.RegisterVo;
import com.atguigu.educenter.entity.UcenterMember;
import com.atguigu.educenter.service.UcenterMemberService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2022-07-20
 */
@RestController
@RequestMapping("/educenter/member")
@CrossOrigin//跨域
public class UcenterMemberController {

    //注入UcenterMemberService接口
    @Autowired
    private UcenterMemberService memberService;

    //登录
    @ApiOperation(value = "会员登录")
    @PostMapping("login")//get提交，GET请求不能接收requestbody中的数据
    public R loginUser(@RequestBody UcenterMember member) {
        //调用Service接口中的方法实现登录
        //返回Token值，使用JWT生成
        String token = memberService.login(member);
        return R.ok().data("token",token);

    }

    //注册
    @ApiOperation(value = "会员注册")
    @PostMapping("register")//RequestBody的作用是将前端传来的json格式的数据转为自己定义好的javabean对象
    public R register(@RequestBody RegisterVo registerVo) {
        memberService.register(registerVo);//接口对象调用注册方法
        return R.ok();
    }

    //根据Token获取用户信息
    @ApiOperation(value = "根据token获取登录信息")
    @GetMapping("getMemberInfo")
    public  R getMemberInfo(HttpServletRequest request) {
        //调用JWT工具栏的方法,根据request对象获取用户ID
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        //查询数据库根据用户ID获取用户信息
        UcenterMember member = memberService.getById(memberId);
        return R.ok().data("userInfo",member);

    }

    //根据用户id，获取用户信息
    @PostMapping("getUserInfoOrder/{id}")
    public UcenterMemberOrder getUserInfoOrder(@PathVariable String id) {
        UcenterMember member = memberService.getById(id);
        //把member对象里的值复制给ucenterMemberOrder对象
        UcenterMemberOrder ucenterMemberOrder = new UcenterMemberOrder();
        BeanUtils.copyProperties(member,ucenterMemberOrder);
        return ucenterMemberOrder;
    }

    //查询一天的注册人数
    @GetMapping("countRegister/{day}")
    public R countRegister(@PathVariable String day) {
        int count = memberService.countRegisterDay(day);
        return R.ok().data("countRegister",count);
    }
}

